import AntModal from '@/components/pt/dialog/AntModal'
import AdvanceTable from '@/components/pt/table/AdvanceTable'
import { addBizCustomerAccount,payableDetailExportExcel } from '@/api/biz/bizCustomerAccount'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getInitData} from '@/api/biz/bizOrder'
import { detailList } from '@/api/biz/bizCustomerPayable'
import tableDragResizeMixin from '@/mixins/tableDragResizeMixin'
import listMixin from '@/mixins/listMixin';
import moment from 'moment'
export default {
  name: 'CreateForm',
  components: {
    AntModal,
    AdvanceTable
  },
  mixins: [tableDragResizeMixin,listMixin],
  data() {
    return {
      printUrl:'/api/biz/bizcustomerpayable/detailExport?Authorization='+storage.get(ACCESS_TOKEN),
      open: false,
      openPrint: false,
      closeDialog: true,
      spinning: false,
      delayTime: 100,
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      loading: false,
      disabled: false,
      total: 0,
      id: undefined,
      formTitle: '添加销售单',
      statusOptions:[],
      statementOptions:[],
      selectedRows:[],
      currentSelectedRowKeys:[],
      currentSelectedRows:[],
      statusArr:[],
      isorter:{},
      orderDate:undefined,
      setUrl:'',
      linked:true,
      isPageChange:false,//用于确认是否第一次翻页
      select:false,
      // 表单参数
      form: {
        accountStatus:'1',
        orderParams:''
      },
      queryParam:{
        pageNum:1,
        pageSize:11,
        pageSizeOptions:['11','21','51','101','201','501','1001'],
      },
      columns: [
        {
          title: '销售单号',
          dataIndex: 'orderNumber',
          align: 'center',
          sorter:true,
        },
        {
          title: '客户',
          dataIndex: 'customerName',
          align: 'center',
          sorter:true,
        },
        {
          title: '地址',
          dataIndex: 'newAddress',
          align: 'center',
          sorter:true,
        },
        {
          title: '联系电话',
          dataIndex: 'newPhone',
          align: 'center',
          sorter:true,
        },
        
        {
          title: '产品编号',
          dataIndex: 'productCode',
          ellipsis: true,
          align: 'left',
          width: '12.8%',
          sorter:true,
        },
        {
          title: '型号',
          dataIndex: 'model',
          align: 'right',
          width: '12.8%',
          sorter:true,
        },
        {
          title: '颜色',
          dataIndex: 'color',
          align: 'center',
          width:'8%',
          sorter:true,
        },
        {
          title: '规格',
          dataIndex: 'spec',
          align: 'center',
          width:'8%',
          sorter:true,
        },
        {
          title: '品牌',
          dataIndex: 'brand',
          align: 'center',
          width:'8%',
          sorter:true,
        },
        {
          title: '数量',
          dataIndex: 'number',
          align: 'right',
          width: '12.8%',
          sorter:true,
          scopedSlots: {
            customRender: 'numberSlot'
          }
        },
        {
          title: '单价',
          dataIndex: 'price',
          align: 'right',
          width: '12.8%',
          scopedSlots: { customRender: 'priceSlot' },
          sorter:true,
        },
        {
          title: '单位',
          dataIndex: 'unit',
          align: 'right',
          width: '12.8%',
          scopedSlots: {
            customRender: 'unitSlot'
          },
          sorter:true,
        },
        {
          title: '金额',
          dataIndex: 'totalAmount',
          align: 'right',
          width: '12.8%',
          scopedSlots: { customRender: 'amountSlot' },
          sorter:true,
        },
        
        {
          title: '下单日期',
          dataIndex:'orderDate',
          align: 'center'
        },
        {
          title: '销售备注',
          dataIndex: 'newRemark',
          align: 'center',
          width:'8%',
        },
        {
          title: '备注',
          dataIndex: 'detailRemark',
          align: 'center',
        },
        {
          title: '对账单号',
          dataIndex: 'accountCode',
          align: 'center',
          scopedSlots: {
            customRender: 'accountSlot'
          },
          sorter:true,
        },
        {
          title: '对账状态',
          dataIndex: 'accountStatus',
          align: 'center',
          scopedSlots: {
            customRender: 'accountStatus'
          },
        },
        {
          title: '单据阶段',
          dataIndex: 'orderStatus',
          align: 'center',
          scopedSlots: {
            customRender: 'orderStatus'
          }
        },
      ],
      list: [],
      selectedRowKeys: [],
      ids: [],
      fileList: [],
      currentDay: moment().format('YYYY-MM-DD'),
      allList:[],
    }
  },
  filters: {},
  created() { 
    this.initColumnsSetting('receivableDetail')
    getInitData('order_status,statement_status').then((response) => {
      this.statusOptions = (response.data.order_status || []).filter(v=>!(['1','2'].includes(v.dictValue)) ) //过滤掉待审核，已审核
      this.statementOptions = response.data.statement_status
    })
  },
  computed: {},
  watch: {
    currentSelectedRows(newValue, oldValue) {
      console.log('newValue :>> ', newValue);
      console.log('oldValue :>> ', oldValue);
    }
  },
  mounted() { },
  methods: {
    statusFormat(row) {
      return this.selectDictLabel(this.statusOptions, row.orderStatus)
    },
    statementFormat(row) {
      return this.selectDictLabel(this.statementOptions, row.accountStatus)
    },
    
    getCheckboxProps(record) {
      return { props: { disabled: !!record.accountCode } }
    },
    onClose() {
      this.open = false
      this.select = false
      this.reset()
      this.$emit('close')
    },
    // 取消按钮
    cancel() {
      console.log('cancel')
      this.open = false
      this.select = false
      this.reset()
      this.$emit('close')
    },
    
    /** 翻页操作 */
    onShowSizeChange(current, pageSize) {
      console.log('this.selectedRowKeys :>> ', this.selectedRowKeys);
      this.queryParam.pageSize = pageSize
      this.getDetailList()
    },
    /** 翻页操作 */
    onSizeChange(current, size) {
      this.queryParam.pageNum = 1
      this.queryParam.pageSize = size
      this.getDetailList()
    },
    /** 翻页操作 */
    changeSize(current, pageSize) {
      this.queryParam.pageNum = current
      this.queryParam.pageSize = pageSize
      this.getDetailList()
    },
    // 表单重置
    reset() {
      this.form = {}
    },
    handleDetail(row) {
      this.reset()
      this.open = true
      this.formTitle = '应收账款明细';
      this.form.customerId = row.customerId
      this.form.customerName = row.customerName
      this.$set(this.form,'accountStatus','1')
      this.orderDate = [moment(this.currentDay).startOf('month'), moment(moment(this.currentDay).endOf('month').format("YYYY-MM-DD"),"YYYY-MM-DD")]
      this.getDetailList()
    },
    handleSelectDetail(row) {
      this.reset()
      this.open = true
      this.select = true
      this.formTitle = '请选择应收账款明细';
      this.form.customerId = row.customerId
      this.form.customerName = row.customerName
      this.$set(this.form,'accountStatus','1')
      this.orderDate = [moment(this.currentDay).startOf('month'), moment(moment(this.currentDay).endOf('month').format("YYYY-MM-DD"),"YYYY-MM-DD")]
      this.getDetailList()
    },
    getDetailList(){
      this.loading = true
      if(this.orderDate && this.orderDate.length>0) {
        this.form.startDate=this.orderDate[0].format('yyyy-MM-DD');
      } else {
        this.form.startDate=undefined;
      }
      if(this.orderDate && this.orderDate.length>1) {
        this.form.endDate = this.orderDate[1].format('yyyy-MM-DD');
      } else {
        this.form.endDate=undefined;
      }
      console.log('this.form.orderParams :>> ', this.form.orderParams);
      let param ={
        accountStatus:this.form.accountStatus,
        orderStatus:this.statusArr.join(','),
        customerId:this.form.customerId,
        pageNum:this.queryParam.pageNum,
        pageSize:this.queryParam.pageSize - 1,
        order: this.form.order,
        column: this.form.column,
        orderParams: this.form.orderParams && this.form.orderParams.trim(),
        endDate:this.form.endDate,
        startDate:this.form.startDate,
      }
      detailList(param).then(res=>{
        this.loading = false
        if(res.code == 200) {
          let result = (res.data.list || []).map(v=>(v.pageNum = this.queryParam.pageNum,v))
          this.form.list = result
          this.queryParam.pageNum = res.data.pageNum
          this.total = res.data.total
          this.tableAddTotalRow(this.columns,this.form.list)
        }else{
          this.message.error(res.msg)
        }
      }).catch(e=>{
        this.loading = false
      })
    },
    
    resetQuery(){
      this.form.accountStatus = ''
      this.form.orderStatus = ''
      this.form.orderParams = ''
      this.statusArr = []
      this.getDetailList()
    },
    /** 提交按钮 */
    submitForm: function (closeDialog) {
      this.closeDialog = closeDialog
      this.disabled = true
      if(!this.selectedRows || !this.selectedRows.length){
        this.$message.error('请选择未生成对账的单据！')
        this.disabled = false
        return
      }
      this.$refs.form.validate(valid => {
        if (valid) {
          let data = {customerId:this.form.customerId,payableDetails:this.selectedRows.map((v,index)=>(v.sort=index,v))}
          const saveForm = JSON.parse(JSON.stringify(data))
          addBizCustomerAccount(saveForm).then(response => {
            this.$message.success('操作成功', 3)
            this.open = false
            this.$emit('ok')
            this.$emit('close')
            this.disabled = false
          }).catch(e=>{
            this.disabled = false
          })
        } else {
          this.disabled = false
          return false
        }
      })
    },
    submitSelect(){
      this.disabled = true
      if(!this.selectedRows || !this.selectedRows.length){
        this.$message.error('请选择未生成对账的单据！')
        this.disabled = false
        return
      }
      this.$emit('ok',this.selectedRows)
      this.onClose()
    },
    // 单选逻辑
    onSelectChange(selectedRowKeys, selectedRows) {
      if (!this.linked){
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
        this.ids = this.selectedRows.map(item => item.id)
      }
    },
    // 多选逻辑
    onSelect(row){
      if (this.linked) {
        if (this.selectedRowKeys.includes(row.id)) {
          // 删除
          let index = this.selectedRowKeys.findIndex(v=>v === row.id)
          if (index > -1) {
            this.selectedRowKeys.splice(index,1)
          }
          let rowIndex = this.selectedRows.findIndex(v=>v.id === row.id)
          if (rowIndex > -1) {
            this.selectedRows.splice(index,1)
          }
        }else{
          let rows = this.form.list.filter(v=>v.orderNumber === row.orderNumber && !v.accountCode)
          rows.forEach(val=>{
            if (!this.selectedRowKeys.includes(val.id)) {
              this.selectedRowKeys.push(val.id)
              this.selectedRows.push(val)
            }
          })
        }
        this.ids = this.selectedRows.map(item => item.id)
        this.$forceUpdate()
      }
    },
    /**
     * @排序
     * @param {obj} pagination 
     * @param {*} filters 
     * @param {*} sorter 
     */
    handleTableChange (pagination, filters, sorter) {
      console.log('pagination :>> ', pagination);
      this.isPageChange = true
      //分页、排序、筛选变化时触发
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
        this.form.order = this.isorter.order
        this.form.column = this.isorter.column
      }
      if (pagination && pagination.current) {
        this.form.pageNum = pagination.current
        this.form.pageSize = pagination.pageSize
      }
      this.getDetailList()
    },
    /**
     * @打印
     * @returns 
     */
    print() {
      let param = {}
      if(this.selectedRows.length){
        param = {
          accountCode:this.selectedRows[0].accountCode
        }
      }else{
        return this.$message.error('请选择一条数据')
      }
      let ids = this.selectedRowKeys.join(',')
      this.setUrl =   `${this.printUrl}&ids=${ids}&customerName=${this.form.customerName}`
      this.openPrint = true;
    },
    
    /** 导出按钮操作 */
    exportExcel () {
      var that = this,param
      if(this.selectedRows.length){
        param = {
          ids:this.selectedRowKeys.join(','),
          customerName:this.form.customerName
        }
      }else{
        return this.$message.error('请选择一条数据')
      }
      this.$confirm({
        title: '是否确认导出?',
        content: '此操作将导出当前条件下所有数据而非选中数据',
        onOk () {
          return payableDetailExportExcel(param)
            .then(response => {
              that.download(response.msg)
              that.$message.success(
                '导出成功',
                3
              )
          })
        },
        onCancel () {}
      })
    },
  }
}
